package com.linln.admin.ws.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.thread.ExecutorBuilder;
import cn.hutool.json.JSONUtil;
import com.dtflys.forest.http.ForestResponse;
import com.linln.admin.ws.api.MessageApi;
import com.linln.admin.ws.api.PhoneMessage;
import com.linln.admin.ws.domain.*;
import com.linln.admin.ws.repository.BusinessApiRepository;
import com.linln.admin.ws.repository.MubanRepository;
import com.linln.admin.ws.repository.SendPhoneRepository;
import com.linln.admin.ws.repository.WsUserRepository;
import com.linln.admin.ws.service.WsUserService;
import com.linln.common.data.PageSort;
import com.linln.common.enums.StatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.stream.Collectors;

/**
 * @author sh
 * @date 2023/01/05
 */
@Service
@Slf4j
public class WsUserServiceImpl implements WsUserService {

    @Autowired
    private WsUserRepository wsUserRepository;

    @Autowired
    private MubanRepository mubanRepository;

    @Autowired
    private SendPhoneRepository sendPhoneRepository;

    @Autowired
    private BusinessApiRepository businessApiRepository;

    @Autowired
    private MessageApi messageApi;

    public static final ExecutorService wsUserPool = ExecutorBuilder.create()
            .setCorePoolSize(3)
            .setMaxPoolSize(3)
            .setWorkQueue(new LinkedBlockingQueue<>(30000))
            .build();

    /**
     * 根据ID查询数据
     * @param id 主键ID
     */
    @Override
    public WsUser getById(Long id) {
        return wsUserRepository.findById(id).orElse(null);
    }

    /**
     * 获取分页列表数据
     * @param example 查询实例
     * @return 返回分页数据
     */
    @Override
    public Page<WsUser> getPageList(Example<WsUser> example) {
        // 创建分页对象
        PageRequest page = PageSort.pageRequest();
        return wsUserRepository.findAll(example, page);
    }

    /**
     * 保存数据
     * @param wsUser 实体对象
     */
    @Override
    public WsUser save(WsUser wsUser) {
        return wsUserRepository.save(wsUser);
    }

    /**
     * 状态(启用，冻结，删除)/批量状态处理
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateStatus(StatusEnum statusEnum, List<Long> idList) {
        return wsUserRepository.updateStatus(statusEnum.getCode(), idList) > 0;
    }

    @Override
    public void sendMessage(SendMessageDTO sendMessageDTO) {

        Long mubanId = sendMessageDTO.getMubanId();
        String ids = sendMessageDTO.getIds();

        if (StringUtils.isBlank(ids)){
            return;
        }
        List<Long> wsUserList = JSONUtil.toList(ids , Long.class);
        Long apiId = sendMessageDTO.getApiId();
        Long phoneId = sendMessageDTO.getPhoneId();

        
        //获取模板
        Muban muban = mubanRepository.getById(Long.valueOf(mubanId));
        if (Objects.isNull(muban)){
            log.warn("模板为空");
            return;
        }
        //发送手机号
        SendPhone sendPhone = sendPhoneRepository.getById(phoneId);
        if (Objects.isNull(sendPhone)){
            log.warn("sendPhone为空");
            return;
        }
        //企业api账户
        BusinessApi businessApi = businessApiRepository.getById(apiId);
        if (Objects.isNull(businessApi)){
            log.warn("企业账号为空");
            return;
        }
        //接收用户手机
        List<WsUser> wsUsers = wsUserRepository.findAllById(wsUserList);
        if (CollectionUtils.isEmpty(wsUsers)){
            log.info("没有接收方");
            return;
        }
        log.info("发送手机个数:{}" , wsUsers.size());

        for (WsUser wsUser : wsUsers) {

            WsUser copyWsUser = BeanUtil.copyProperties(wsUser , WsUser.class);
            wsUserPool.submit( ()->{
                try {
                    PhoneMessage phoneMessage = new PhoneMessage();
                    phoneMessage.setTo(wsUser.getWsPhone());
                    phoneMessage.setType("template");
                    phoneMessage.setMessagingProduct("whatsapp");

                    PhoneMessage.TemplateDTO templateDTO = new PhoneMessage.TemplateDTO();
                    PhoneMessage.TemplateDTO.LanguageDTO languageDTO = new PhoneMessage.TemplateDTO.LanguageDTO();
                    languageDTO.setCode("en_US");
                    templateDTO.setLanguage(languageDTO);
                    templateDTO.setName(muban.getApiName());
                    phoneMessage.setTemplate(templateDTO);


                    log.info("sendMessage:{}" , JSONUtil.toJsonStr(phoneMessage));
                    try {
                        String result = messageApi.sendMessage(businessApi.getToken(), sendPhone.getPhoneId(), phoneMessage);
                        log.info("result:{}" , result);
                        Integer sendCount = copyWsUser.getSendCount();
                        sendCount = Objects.isNull(sendCount) ? 0 : sendCount;
                        copyWsUser.setSendCount(sendCount + 1);
                        wsUserRepository.save(copyWsUser);


                    }catch (Exception e ){
                        log.warn("sendMessage,warn" , e);
                    }
                }catch (Exception e ){
                    log.warn("wsUserPoolwarn" , e);
                }
            });

        }




    }
}